/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client.user;

import net.bioteam.appweb.gwt.apps.client.StaticHolder;
import net.bioteam.appweb.gwt.apps.client.Util.ApplicationCallBack;
import net.bioteam.appweb.gwt.apps.client.Util.GwtRpcDataSource;
import net.bioteam.appweb.gwt.apps.clientandserver.user.JobRet;
import net.bioteam.appweb.gwt.apps.clientandserver.user.UserAction;
import net.bioteam.appweb.submit.RunStatus;

import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.data.fields.DataSourceDateTimeField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class JobsDataSource extends GwtRpcDataSource
{

	private static void copyValues(RunStatus from, ListGridRecord to)
	{
		to.setAttribute("id", from.getId());
		to.setAttribute("jobID", from.getJobid()==null?from.getRemoteJobId():from.getJobid());
		to.setAttribute("programName", from.getProgramName());
		to.setAttribute("submittedTime", from.getSubmittedTime());
		to.setAttribute("finishedTime", from.getFinishedTime());
		to.setAttribute("exitvalue", from.getExitValue());
		to.setAttribute("code", from.getCode().toString());
		to.setAttribute("workdir", from.getWorkdirName());
		to.setAttribute("files", "folder_go");
		to.setAttribute("clusterid", from.getClusterid());
		to.setAttribute("note", from.getNote());
	}

	public JobsDataSource()
	{
		super();
		DataSourceTextField idField = new DataSourceTextField("id");
		idField.setPrimaryKey(true);
		idField.setHidden(true);

		DataSourceTextField jobIDField = new DataSourceTextField("jobID");

		DataSourceTextField programNameField = new DataSourceTextField("programName");

		DataSourceDateTimeField submitTimeField = new DataSourceDateTimeField("submitTime");
		DataSourceDateTimeField finishTimeField = new DataSourceDateTimeField("finishTime");

		DataSourceIntegerField exitCodeField = new DataSourceIntegerField("exitCode");
		DataSourceTextField statusField = new DataSourceTextField("status");
		DataSourceTextField workdirField = new DataSourceTextField("workdir");
		workdirField.setHidden(true);
		
		DataSourceTextField filesField = new DataSourceTextField("files");
		DataSourceTextField noteField = new DataSourceTextField("note");
		DataSourceIntegerField remoteField=new DataSourceIntegerField("clusterid");
		setFields(idField, jobIDField, programNameField, submitTimeField, finishTimeField, exitCodeField, statusField, workdirField, filesField, remoteField, noteField);
	}

	@Override
	protected void executeAdd(String requestId, DSRequest request, DSResponse response)
	{
		//this is not supported
		response.setStatus(RPCResponse.STATUS_FAILURE);
		processResponse(requestId, response);
	}

	@Override
	protected void executeFetch(final String requestId, final DSRequest request, final DSResponse response)
	{
		ApplicationCallBack<JobRet> callback = new ApplicationCallBack<JobRet>()
		{

			public void onFailureAfter(Throwable caught)
			{
				
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(JobRet result)
			{

				ListGridRecord[] list = new ListGridRecord[result.statuses.length];
				for (int i = 0; i < list.length; i++)
				{
					ListGridRecord record = new ListGridRecord();
					copyValues(result.statuses[i], record);
					list[i] = record;

				}
				
				response.setData(list);
				// IMPORTANT: for paging to work we have to specify size of full result set
				//response.setStartRow(request.getStartRow());
				//response.setEndRow(request.getStartRow()+list.length);
                response.setTotalRows (result.count);
				processResponse(requestId, response);

			}

			public void execute()
			{
				String sort =null;
				String direction = "asc";
				if (request.getSortBy()!=null && request.getSortBy().length>0)
				{
					SortSpecifier ss=request.getSortBy()[0];
					sort=ss.getField();
					direction=ss.getSortDirection().getValue();
				}
				UserAction.Util.getInstance().getJobs(request.getStartRow(), request.getEndRow() - request.getStartRow(), sort, direction, this);
			}

		};
		callback.execute();

	}


	protected void executeBatchRemove(final ListGridRecord[] recs, final JobGrid grid)
	{
		 
	        ApplicationCallBack<String> callback = new ApplicationCallBack<String>()
			{

				public void onFailureAfter(Throwable caught)
				{
					grid.reload();
				}

				public void onSuccessAfter(String result)
				{
					grid.reload();
				}

				public void execute()
				{

					String ids[]=new String[recs.length];
					for (int i=0; i<recs.length; i++)
						ids[i]=recs[i].getAttributeAsString("id");
					UserAction.Util.getInstance().deleteJobs(ids, this);
				}

			};
			callback.execute();

	}
	
	protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response)
	{
		 JavaScriptObject data = request.getData ();
	        final ListGridRecord rec = new ListGridRecord (data);
	        ApplicationCallBack<String> callback = new ApplicationCallBack<String>()
			{

				public void onFailureAfter(Throwable caught)
				{
					
					response.setStatus(RPCResponse.STATUS_FAILURE);
					processResponse(requestId, response);
					SC.warn(caught.getMessage(), StaticHolder.dumpB);
				}

				public void onSuccessAfter(String result)
				{
					ListGridRecord[] list = new ListGridRecord[1];
	                // We do not receive removed record from server.
	                // Return record from request.
	                list[0] = rec;
	                response.setData (list);
	                processResponse (requestId, response);

				}

				public void execute()
				{

					String ids[]=new String[1];
					ids[0]=rec.getAttributeAsString("id");
					UserAction.Util.getInstance().deleteJobs(ids, this);
				}

			};
			callback.execute();

	}

	@Override
	protected void executeUpdate(String requestId, DSRequest request, DSResponse response)
	{
		//this is not supported
		response.setStatus(RPCResponse.STATUS_FAILURE);
		processResponse(requestId, response);

	}

}
